import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom';
import { toast } from 'react-toastify';
import { Table, Button, Space, Modal, Spin, Empty, Select } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';

import './Users.css';

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [confirmDelete, setConfirmDelete] = useState({ show: false, userId: null });
  const navigate = useNavigate();

  // 表格列定义
  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
    { title: '用户名', dataIndex: 'username', key: 'username' },
    { title: '姓名', dataIndex: 'full_name', key: 'full_name', render: name => name || '-' },
    { title: '邮箱', dataIndex: 'email', key: 'email', render: email => email || '-' },
    { 
      title: '角色', 
      dataIndex: 'role', 
      key: 'role',
      render: (role, record) => (
        record.username === 'admin' ? (
          <span className="role-badge role-admin">管理员</span>
        ) : (
          <Select
            value={role}
            onChange={newRole => handleRoleChange(record.id, newRole)}
            style={{ width: 120 }}
          >
            <Select.Option value="payment_manager">清算经理</Select.Option>
            <Select.Option value="employee">员工</Select.Option>
          </Select>
        )
      )
    },
    { 
      title: '创建时间', 
      dataIndex: 'created_at', 
      key: 'created_at',
      render: time => new Date(time).toLocaleString()
    },
    { 
      title: '操作', 
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => navigate(`/users/${record.id}/edit`)}
          >
            编辑
          </Button>
          {record.username !== 'admin' && (
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDeleteClick(record.id)}
            >
              删除
            </Button>
          )}
        </Space>
      )
    }
  ];

  // 获取用户列表
  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const res = await axios.get('/users');
      setUsers(res.data || []);
    } catch (err) {
      console.error('获取用户列表失败', err);
      setError('获取用户列表失败，请刷新页面重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除用户
  const handleDeleteClick = (userId) => {
    setConfirmDelete({ show: true, userId });
  };

  const confirmDeleteUser = async () => {
    if (!confirmDelete.userId) return;

    try {
      await axios.delete(`/users/${confirmDelete.userId}`);
      setUsers(users.filter(user => user.id !== confirmDelete.userId));
      toast.success('用户已删除');
    } catch (err) {
      console.error('删除用户失败', err);
      toast.error(err.response?.data?.message || '删除用户失败，请稍后重试');
    } finally {
      setConfirmDelete({ show: false, userId: null });
    }
  };

  const cancelDelete = () => {
    setConfirmDelete({ show: false, userId: null });
  };

  // 更新用户角色
  const handleRoleChange = async (userId, newRole) => {
    try {
      await axios.patch(`/users/${userId}/role`, { role: newRole });
      setUsers(users.map(user =>
        user.id === userId ? { ...user, role: newRole } : user
      ));
      toast.success('用户角色已更新');
    } catch (err) {
      console.error('更新用户角色失败', err);
      toast.error('更新角色失败，请稍后重试');
    }
  };

  if (error) {
    return <div className="error-message">{error}</div>;
  }

  return (
    <div className="user-list-container">
      <div className="user-list-header">
        <h1 className="page-title">用户管理</h1>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => navigate('/admin/add-user')}
        >
          添加用户
        </Button>
      </div>

      <Spin spinning={loading} tip="加载用户列表中...">
        <Table
          columns={columns}
          dataSource={users.map(user => ({ ...user, key: user.id }))}
          rowKey="id"
          locale={{ emptyText: <Empty description="暂无用户数据" /> }}
          pagination={{ pageSize: 10 }}
        />
      </Spin>

      {/* 删除确认对话框 */}
      <Modal
        title="确认删除"
        open={confirmDelete.show}
        onOk={confirmDeleteUser}
        onCancel={cancelDelete}
        okText="删除"
        cancelText="取消"
        destroyOnClose
      >
        <p>您确定要删除此用户吗？此操作无法撤销。</p>
      </Modal>
    </div>
  );
};

export default UserList;